package com.geekgo.lucenepp.core.config.index.impl;

import com.geekgo.lucenepp.core.config.datasource.LuceneDataSource;
import com.geekgo.lucenepp.core.config.index.IndexFactory;
import com.geekgo.lucenepp.util.DateUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 添加索引
 *
 * @author HeHaoyang
 * @create 2017-06-13 18:33
 **/
public class AddIndex implements IndexFactory {

    private Logger log = LoggerFactory.getLogger(AddIndex.class);

    @Override
    public boolean saveIndex(LuceneDataSource dataSource, Document document) {
        long startTime = DateUtil.getDate();
        boolean flag = true;
        IndexWriter indexWriter = dataSource.getIndexWriter();
        try {
            indexWriter.addDocument(document);
            long commit = indexWriter.commit();
            log.info("新增索引数量:"+commit);
        } catch (IOException e) {
            flag = false;
            log.error("新增索引失败",e);
        }
        DateUtil.timeConsuming("新增内核", startTime);
        return flag;
    }

    @Override
    public boolean saveIndexs(LuceneDataSource dataSource, List<Document> documents) {
        long startTime = DateUtil.getDate();
        boolean flag = true;
        IndexWriter indexWriter = dataSource.getIndexWriter();
        try {
            indexWriter.addDocuments(documents);
            long commit = indexWriter.commit();
            log.info("新增索引数量:"+commit);
        } catch (IOException e) {
            flag = false;
            log.error("新增索引失败",e);
        }
        DateUtil.timeConsuming("新增内核", startTime);
        return flag;
    }
}
